package db

import (
	"encoding/json"
	"errors"
)

type ModelData struct {
	Key    string  `json:"key"`
	UID    int64   `json:"uid"`
	Values []int64 `json:"values"`
	Model  Model   `json:"-"`
}

type Model interface {
	GetTable() (table string, structure interface{})
	SaveToMysql(uid int64) (err error)
	SyncIfNotExist(uid int64, data interface{}) (exist bool, err error)
}

var Models = make(map[string]Model)
var ErrNotFoundModel = errors.New("未找到model")

func RegisterModel(key string, model Model) {
	Models[key] = model
}

func DecodeModel(content string) (conf *ModelData, err error) {
	conf = new(ModelData)
	err = json.Unmarshal([]byte(content), conf)
	if err != nil {
		return
	}

	m, found := Models[conf.Key]
	if !found {
		return nil, ErrNotFoundModel
	}
	conf.Model = m
	return
}
